import { message } from 'antd'
import { ServerResult } from '../../server/interface'
export const Fetch = async function <T, F> (url: string, data?: T, options: RequestInit = {}): Promise<ServerResult<F>> {
    const method = data ? 'POST' : (options.method || 'GET')
    const body = (data instanceof FormData || data instanceof Blob || data instanceof ArrayBuffer) ? data : (
        data ? JSON.stringify(data) : undefined
    )
    const response = await fetch(url, {
        method,
        headers: {
            'Content-Type': 'application/json',
            ...options.headers,
        },
        body,
        ...options,
    })
    const res: ServerResult<F> = await response.json()
    if (!res.success && res.msg) {
        message.error(res.msg)
    }
    return res
}

export const createFetch = function (cfg: {baseUrl: string}) {
    return async function <T, F> (url: string, data?: T, options: RequestInit = {}): Promise<ServerResult<F>> {
        return Fetch(cfg.baseUrl + url, data, options)
    } 
}